﻿using JHECIS.BLL.Triage.DataServices;
using JHECIS.DataModel;
using JHECIS.DataModel.Common;
using JHECIS.DataModel.DictModel;
using JHECIS.DataModel.SysConfig;
using JHECIS.DataModel.Triage;
using JHECIS.Interface;
using JHECIS.TriageDataService.Entity;
using Microsoft.Practices.ServiceLocation;
using MS.Common;
using MS.Common.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading;

namespace JHECIS.BLL.Triage.Common
{
    /// <summary>
    /// 分诊JS接口通用类 袁凤超 2022-03-28
    /// </summary>
    internal class InterfaceToolHelper
    {
        #region 属性
        /// <summary>
        /// 延迟加载对象 袁凤超 2022-03-28
        /// </summary>
        private static readonly Lazy<InterfaceToolHelper> _lazy =
            new Lazy<InterfaceToolHelper>(() => new InterfaceToolHelper(), LazyThreadSafetyMode.PublicationOnly);

        /// <summary>
        /// 单例对象 袁凤超 2022-03-28
        /// </summary>
        public static InterfaceToolHelper Instance => _lazy.Value;
        /// <summary>
        /// 接口工具服务接口  袁凤超 2022-03-28
        /// </summary>
        private readonly IInterfaceToolService jsService;

        /// <summary>
        /// 接口工具  袁凤超  2022-01-27
        /// </summary>
        private readonly IRestClient client;
        #endregion

        #region 构造方法
        /// <summary>
        /// 构造方法  袁凤超 2022-03-28
        /// </summary>
        private InterfaceToolHelper()
        {
            jsService = ServiceLocator.Current.GetInstance<IInterfaceToolService>();
            client = ServiceLocator.Current.GetInstance<IRestClient>();
        }
        #endregion

        #region 公用方法
        /// <summary>
        /// 去除用户的登录日志、权限列表
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private static JObject GetUserInfo(SysUser user)
        {
            var userInfo = JObject.FromObject(user);
            userInfo.Remove(nameof(user.PERMISSIONLIST));
            userInfo.Remove(nameof(user.LogInLogData));
            userInfo.Remove(nameof(user.OpenFireUser));
            return userInfo;
        }
        /// <summary>
        /// 通用JS方法  袁凤超 2022-03-28
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="funcName">接口方法名</param>
        /// <param name="data">入参</param>
        /// <returns></returns>
        public CommonResult CallJsConvert<T>(string funcName, string data) where T : class
        {
            try
            {
                var jsScript = jsService.GetInterfaceToolByCode(funcName);
                if (jsScript != null)
                {
                    var script = new ScriptContent()
                    {
                        FunctionName = jsScript.FUNCTIONNAME,
                        JavaScriptCode = jsScript.JAVASCRIPTCODE,
                        Data = data
                    };
                    string respone = jsService.Convert(script);
                    var result = JsonConvert.DeserializeObject<CommonResult>(respone);
                    if (result.Result)
                    {
                        var list = JsonConvert.DeserializeObject<T>(Convert.ToString(result.ReturnData));
                        result.ReturnData = list;
                    }
                    return result;
                }
                else
                {
                    return new CommonResult() { Result = false, ReturnData = null, ErrMsg = $"请配置接口工具【{funcName}】！" };
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
                return new CommonResult() { Result = false, ReturnData = null, ErrMsg = $"网络出现问题【{funcName}】！" };
            }
        }

        /// <summary>
        /// 传入接口方法名，与动态参数获取接口工具方法执行结果 袁凤超 2022-03-01
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="funcName"></param>
        /// <param name="param"></param>
        /// <param name="existNull">当接口不存时是否返回null</param>
        /// <returns></returns>
        public CommonResult CallJsConvertDynamic(string funcName, object param, bool existNull = false)
        {
            CommonResult result = new CommonResult();
            try
            {
                var jsScript = jsService.GetInterfaceToolByCode(funcName);
                if (jsScript != null)
                {
                    var script = new ScriptContent()
                    {
                        FunctionName = jsScript.FUNCTIONNAME,
                        JavaScriptCode = jsScript.JAVASCRIPTCODE,
                        Data = JsonConvert.SerializeObject(param, new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss" })
                    };
                    string respone = jsService.Convert(script);
                    result = JsonConvert.DeserializeObject<CommonResult>(respone);
                    return result;
                }
                else
                {
                    if (existNull)
                        return null;
                    result.Result = false;
                    result.ErrMsg = $"请配置接口【{funcName}】";
                    return result;
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.ErrMsg = ex.Message;
                return result;
            }
        }



        #endregion

        #region 业务操作，API交互
        /// <summary>
        /// 新增群伤 袁凤超 2022-11-05
        /// </summary>
        /// <param name="pvid"></param>
        /// <returns></returns>
        public ResponseApi<CommonResult> AddGroupInjuryUsers(Tr_GroupInjuryInfo groupInjuryInfo)
        {
            var result = new ResponseApi<CommonResult>();
            try
            {
                var request = new RestRequest("api/Triage/AddGroupInjuryUsers", Method.POST);
                var json = JsonConvert.SerializeObject(groupInjuryInfo);
                request.AddJsonBody(json);
                IRestResponse response = client.Execute(request);
                var responseApi = JsonConvert.DeserializeObject<ResponseApi<CommonResult>>(response.Content);
                result = responseApi;
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
            }
            return result;
        }

        #endregion

        #region 接口工具交互
        /// <summary>
        /// 根据患者id获取历史信息 袁凤超 2023-05-30
        /// </summary>
        /// <param name="pvid"></param>
        /// <returns></returns>
        public CommonResult GetChangeRecord(string pvid)
        {
            dynamic param = new System.Dynamic.ExpandoObject();
            param.PVID = pvid;
            CommonResult GetCallResult = CallJsConvertDynamic("TriageChangeRecord", param);
            return GetCallResult;
        }

        /// <summary>
        /// 根据患者id获取绿通信息 袁凤超 2022-03-08
        /// </summary>
        /// <param name="pvid"></param>
        /// <returns></returns>
        public Green_ChannelInfo GetPatientGreen(string pvid)
        {
            Green_ChannelInfo GreenChannelInfo = null;

            dynamic param = new System.Dynamic.ExpandoObject();
            param.Mode = "Get";
            param.PVID = pvid;
            CommonResult GetCallResult = CallJsConvertGreen(param);
            if (GetCallResult != null && GetCallResult.Result && GetCallResult.ReturnData != null)
            {
                var SetRuleModelList = JsonConvert.DeserializeObject<List<Green_ChannelInfo>>(GetCallResult.ReturnData.ToString());
                if (SetRuleModelList != null)
                    GreenChannelInfo = SetRuleModelList[0];
            }
            return GreenChannelInfo;
        }
        /// <summary>
        /// 通过接口给工具处理分诊界面叫号 袁凤超 2022-03-17
        /// </summary>
        /// <param name="pvid"></param>
        /// <returns></returns>
        public CommonResult SaveItemDict(JHECIS_ITEM_DICT dictModel, bool IsDelete = false)
        {
            dynamic param = new System.Dynamic.ExpandoObject();
            param.IsDelete = IsDelete;
            param.Data = dictModel;
            return CallJsConvertDynamic("TriageItemDict", param);
        }
        /// <summary>
        /// 绿通相关接口请求方法 袁凤超 2022-03-01
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public CommonResult CallJsConvertGreen(dynamic param)
        {
            return CallJsConvertDynamic("GreenChannelApply", param);
        }

        /// <summary>
        /// 接口工具分诊信息回传
        /// </summary>
        /// <param name="pat"></param>
        /// <returns></returns>
        public CommonResult TriageInfoToHIS(Tr_PatientVisitInfo pat)
        {
            string oldJosn = JsonConvert.SerializeObject(pat);
            dynamic DyModel = JsonConvert.DeserializeObject<ExpandoObject>(oldJosn);
            DyModel.OpUser = GetUserInfo(UserContext.CurrUser.User);
            return CallJsConvertDynamic("TriageInfoToHIS", DyModel);
        }

        /// <summary>
        /// 接口工具分诊信息删除之前回传
        /// </summary>
        /// <param name="pat"></param>
        /// <returns></returns>
        public CommonResult TriageBeforeDelete(Tr_PatientVisitInfo pat)
        {
            string oldJosn = JsonConvert.SerializeObject(pat);
            dynamic DyModel = JsonConvert.DeserializeObject<ExpandoObject>(oldJosn);
            DyModel.OpUser = GetUserInfo(UserContext.CurrUser.User);
            return CallJsConvertDynamic("TriageBeforeDelete", DyModel,true);
        }

        /// <summary>
        /// 接口工具获取患者信息
        /// </summary>
        /// <param name="pat"></param>
        /// <returns></returns>
        public CommonResult GetHisPatInfo(CardInfo pat)
        {
            string oldJosn = JsonConvert.SerializeObject(pat);
            dynamic DyModel = JsonConvert.DeserializeObject<ExpandoObject>(oldJosn);
            DyModel.OpUser = GetUserInfo(UserContext.CurrUser.User);
            CommonResult result = CallJsConvertDynamic("GetPatInfo", DyModel);
            if (result.Result)
            {
                var list = JsonConvert.DeserializeObject<List<Tr_PatientVisitInfo>>(Convert.ToString(result.ReturnData));
                result.ReturnData = list;
            }
            return result;
        }
        /// <summary>
        /// 接口工具获取三无人员 孙宝 2022-11-18
        /// </summary>
        /// <returns></returns>
        public Tr_PatientVisitInfo GetNoIdPatientInfo()
        {
            Tr_PatientVisitInfo info = new Tr_PatientVisitInfo();
            CommonResult result = CallJsConvert<Tr_PatientVisitInfo>("BuildNoIdPersonRule", string.Empty);
            if (result == null) //未配置接口使用内置规则
            {
                string TempName = "W" + DateTime.Now.ToString("ddHHmmss");
                info.PATIENTID = TempName;
                info.PATIENTNAME = TempName.Substring(0, TempName.Length - 2);
                info.VISITDATE = StaticHelper.TimeNowFor(NowType.Now00);
                info.TRIAGEDT = DateTime.Now;
            }
            else
            {
                info = result.ReturnData as Tr_PatientVisitInfo;
            }
            return info;
        }

        /// <summary>
        /// 接口工具群伤中添加多个患者 袁凤超 2023-02-13
        /// </summary>
        /// <returns></returns>
        public CommonResult GroupMultAddPatient(int patCount)
        {
            string funName = "MultPatientBuild";
            Tr_PatientVisitInfo info = new Tr_PatientVisitInfo();
            dynamic param = new System.Dynamic.ExpandoObject();
            param.PatCount = patCount;
            string input = JsonConvert.SerializeObject(param);
            return CallJsConvert<List<Tr_PatientVisitInfo>>(funName, input);

        }

        /// <summary>
        /// 接口工具建档 孙宝 2022-11-18
        /// </summary>
        /// <param name="triageInfo"></param>
        /// <returns></returns>
        public CommonResult CreatePatInfo(Tr_PatientVisitInfo triageInfo)
        {
            dynamic obj = new System.Dynamic.ExpandoObject();
            obj.Patient = triageInfo;
            obj.User = GetUserInfo(UserContext.CurrUser.User);
            string data = JsonConvert.SerializeObject(obj);
            CommonResult commonResult = CallJsConvertDynamic("CreatePatInfo", data);
            if (commonResult.Result)
            {
                var list = JsonConvert.DeserializeObject<Tr_PatientVisitInfo>(Convert.ToString(commonResult.ReturnData));
                commonResult.ReturnData = list;
            }
            return commonResult;
        }

        /// <summary>
        /// 接口工具获取院前患者 袁凤超 2023-0-19
        /// </summary>
        /// <returns></returns>
        public CommonResult GetEisPatInfos()
        {
            string funName = "GetEisPatInfos";
            try
            {
                return ExCallJsConvert<List<Tr_PatientVisitInfo>>(funName, "");
            }
            catch (Exception ex)
            {
                return new CommonResult() { Result = false, ReturnData = null, ErrMsg = "网络出现问题" };
            }
        }

        /// <summary>
        /// 获取分诊字典接口 袁凤超 2023-08-11
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public CommonResult CallJsDictData(string name)
        {
            dynamic param = new System.Dynamic.ExpandoObject();
            param.Name = name;
            return CallJsConvertDynamic("TriageDictData", param);
        }

        /// <summary>
        /// 通用JS方法  袁凤超 2022-03-28
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="funcName">接口方法名</param>
        /// <param name="data">入参</param>
        /// <returns></returns>
        public CommonResult ExCallJsConvert<T>(string funcName, string data) where T : class
        {
            try
            {
                var jsScript = ExtService.Instance.GetInterfaceToolByCode(funcName);
                if (jsScript != null)
                {
                    var script = new ScriptContent()
                    {
                        FunctionName = jsScript.FUNCTIONNAME,
                        JavaScriptCode = jsScript.JAVASCRIPTCODE,
                        Data = data
                    };
                    string respone = ExtService.Instance.Convert(script);
                    var result = JsonConvert.DeserializeObject<CommonResult>(respone);
                    if (result.Result)
                    {
                        var list = JsonConvert.DeserializeObject<T>(Convert.ToString(result.ReturnData));
                        result.ReturnData = list;
                    }
                    return result;
                }
                else
                {
                    return new CommonResult() { Result = false, ReturnData = null, ErrMsg = $"请配置群伤添加患者接口【{funcName}】！" };
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
                return new CommonResult() { Result = false, ReturnData = null, ErrMsg = $"网络出现问题【{funcName}】！" };
            }
        }

        #endregion
    }
}
